<template>
	<view class="container">
		<view class="form-item">
			<label>姓名</label>
			<input type="nickname" placeholder="请输入姓名" @input="updateName" />
		</view>
		<view class="form-item">
			<label>性别</label>
			<radio-group @change="updateSex">
				<label class="radio">
					<radio value="男" checked /><text>男</text>
				</label>
				<label class="radio">
					<radio value="女" /><text>女</text>
				</label>
			</radio-group>
		</view>

		<view class="form-item">
			<label>电话</label>
			<input type="number" placeholder="请输入电话" @input="updatePhone" />
		</view>
		<view class="form-item">
			<label>毕业学校</label>
			<input type="number" placeholder="请输入毕业学校" @input="updateSchool" />
		</view>
		<view class="form-item">
			<label>学历</label>
			<picker @change="educationalChange" :range="educationalArray">
				<view style="padding: 20rpx;background-color: white;">{{ educational }}</view>
			</picker>
		</view>
		<view class="form-item">
			<label>政治面貌</label>
			<picker @change="politicalChange" :range="politicalArray">
				<view style="padding: 20rpx;background-color: white;">{{ political }}</view>
			</picker>
		</view>
		<view class="form-item">
			<label>执业单位</label>
			<input placeholder="请输入执业单位" @input="updateCompany" />
		</view>
		<view class="form-item">
			<label>执业证号</label>
			<input placeholder="请输入执业证号" @input="updateLicense" />
		</view>
		<view class="form-item">
			<label>请上传执业证照</label>
			<uni-section title="只选择图片" type="line">
				<view class="example-body">
					<uni-file-picker limit="1" title="最多选择1张图片" @select="handleLicenseSelect"
						@delete="handleLicenseDelete"></uni-file-picker>
				</view>
			</uni-section>
		</view>
		<view class="form-item">
			<label>所在城市</label>
			<position-picker @update-region="regionChange"></position-picker>
		</view>
		??????????所在小区后续加入地图??????????
		<view class="form-item">
			<label>详细地址</label>
			<input type="text" placeholder="请输入详细地址" @input="updatePosition" />
		</view>
		<view class="form-item">
			<label>擅长领域</label>
			<input type="text" placeholder='请输入擅长领域,以逗号相隔' @input="updateAreas" />
		</view>
		<view class="form-item">
			<label>简介</label>
			<textarea name="" id="" cols="30" rows="10" placeholder="请输入简介" @input="updateIntroduction"></textarea>
		</view>
		<view class="form-item">
			<label>咨询费</label>
			<input type="digit" placeholder='请输入咨询费' @input="updateMoney" />
		</view>
		<view class="form-item">
			<label>分佣比例</label>
			<input type="digit" placeholder='请输入分佣比例0-1, 默认1, 最低0.05' @input="updateRatio" />
		</view>
		<view class="form-item">
			<label>身份证号</label>
			<input type="idcard" placeholder="请输入身份证号" @input="updateIdCard" />
		</view>
		<view class="form-item">
			<label>请上传身份证反正面照片</label>
			<uni-section title="只选择图片" type="line">
				<view class="example-body">
					<uni-file-picker limit="2" title="最多选择2张图片" @select="handleIdSelect"
						@delete="handleIdDelete"></uni-file-picker>
				</view>
			</uni-section>
		</view>
		<view class="form-item">
			<label>开户行</label>
			<input type="text" placeholder="请输入银行名称" @input="updateBankName" />
		</view>
		<view class="form-item">
			<label>银行卡号</label>
			<input placeholder="请输入银行卡号" @input="updateBankCard" />
		</view>
		<button type="primary" @click="submitForm" @tap="submit">提交申请</button>
		<button type="primary" @click="test">提交申请</button>
	</view>
</template>

<script setup>
	import http from '../../utils/http';
	const educationalArray = ref(['博士', '硕士', '本科', '专科'])
	const educational = ref("请选择学历")
	const politicalArray = ref(['中共党员', '中共预备党员', '共青团员', '群众'])
	const political = ref("请选择政治面貌")

	// 提取字段
	const applicationContent = ref({
		applicationId: "",
		applicationTime: "",
		applicationType: "lawyer",
		currentType: getApp().globalData.user.identity,
		openid: getApp().globalData.user.openid, // 商家的openid
		name: '', // 姓名
		sex: '男', // 性别
		phone: '', // 联系电话
		school: '', // 毕业院校
		educational: '', // 学历
		political: '', // 政治面貌
		company: '', // 执业单位
		license: '', // 执业证号
		region: '', // 所在城市
		position: '', // 详细地址
		longitude: '', // 经度
		latitude: '', // 纬度
		areas: '', // 擅长领域，逗号隔开
		introduction: '', // 简介
		money: '', // 咨询费
		ratio: 1, //分佣比例
		idCard: '', // 身份证号
		bankName: '', // 开户行
		bankCard: '', // 银行卡号
		idImage: [],
		licenseImage: "",
		applicationStatus:"pending"
	});
	const image = ref({
		idCard: [], //身份证正反面照片
		license: "", // 营业执照照片
	})
	// 姓名
	function updateName(e) {
		applicationContent.value.name = e.target.value;
	}
	// 性别
	function updateSex(e){
		applicationContent.value.sex = e.target.value;
	}
	// 电话
	function updatePhone(e) {
		applicationContent.value.phone = e.target.value;
	}
	// 毕业院校
	function updateSchool(e) {
		applicationContent.value.school = e.target.value;
	}
	// 学历
	function educationalChange(e) {
		educational.value = educationalArray.value[e.detail.value]
		applicationContent.value.educational = educationalArray.value[e.detail.value]
	}
	// 政治面貌
	function politicalChange(e) {
		political.value = politicalArray.value[e.detail.value]
		applicationContent.value.political = politicalArray.value[e.detail.value]
	}
	// 执业单位
	function updateCompany(e) {
		applicationContent.value.company = e.target.value
	}
	// 执业证号
	function updateLicense(e) {
		applicationContent.value.license = e.target.value
	}
	// 所在区域
	function regionChange(e) {
		// console.log("position", e[0] + "-" + e[1] + "-" + e[2])
		applicationContent.value.region = e[0] + "-" + e[1] + "-" + e[2]
	}
	// 详细地址
	function updatePosition(e) {
		applicationContent.value.position = e.target.value;
	}
	
	// 擅长领域
	function updateAreas(e) {
		applicationContent.value.areas = e.target.value;
	}
	
	// 简介
	function updateIntroduction(e) {
		applicationContent.value.introduction = e.target.value;
	}
	
	// 咨询费
	function updateMoney(e) {
		applicationContent.value.money = e.target.value;
	}
	
	// 分佣比例
	function updateRatio(e) {
		applicationContent.value.ratio = e.target.value;
	}
	
	// 身份证号
	function updateIdCard(e) {
		applicationContent.value.idCard = e.target.value;
	}
	//身份证正面照片
	function handleIdSelect(e) {
		if (e.tempFiles.length == 0) {
			return;
		}
		for (let i in e.tempFiles) {
			image.value.idCard.push(e.tempFiles[i])
		}

	}

	function handleIdDelete(e) {
		console.log("delete", e)
		image.value.idCard.splice(e.index, 1); // 移除数组中对应的文件
	}

	function handleLicenseSelect(e) {
		image.value.license = e.tempFiles
	}

	function handleLicenseDelete(e) {
		image.value.license = e.tempFiles
	}

	function updateBankName(e) {
		applicationContent.value.bankName = e.target.value
	}

	function updateBankCard(e) {
		applicationContent.value.bankCard = e.target.value
	}

	// 上传文件函数
	async function uploadFile(file, fileType) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'http://localhost:8080/utils/upLoadFile',
				filePath: file.path,
				name: 'file', // 文件字段名
				formData: {
					"filename": generateApplicationId(true, file),
					"applicationId": applicationContent.value.applicationId,
					"type": "lawyerApplication"
				},
				success: (uploadRes) => {
					const res = JSON.parse(uploadRes.data).data;
					if (fileType === 'idCard') {
						applicationContent.value.idImage.push(res)
					} else if (fileType === 'license') {
						applicationContent.value.licenseImage = res;
					} 
					resolve();
				},
				fail: (error) => {
					console.log('上传失败', error);
					reject(error);
				}
			});
		});
	}

	function generateApplicationId(flag, file) {
		const now = new Date();
		const year = now.getFullYear().toString().padStart(4, '0'); // 获取年份并转换为四位数
		const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 获取月份并转换为两位数
		const day = now.getDate().toString().padStart(2, '0'); // 获取日期并转换为两位数
		const hours = now.getHours().toString().padStart(2, '0'); // 获取小时并转换为两位数
		const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟并转换为两位数
		const seconds = now.getSeconds().toString().padStart(2, '0'); // 获取秒并转换为两位数
		const milliseconds = now.getMilliseconds().toString().padStart(3, '0'); // 获取毫秒并转换为三位数

		if (flag == true) {
			// 添加文件类型或文件名作为唯一标识符
			const fileType = file.type || 'unknown'; // 文件类型
			const fileName = file.name || 'unknown'; // 文件名

			return `${year}${month}${day}${hours}${minutes}${seconds}_${milliseconds}_${fileType}_${fileName}`;
		} else
			return `${year}${month}${day}${hours}${minutes}${seconds}_${milliseconds}`;
	}

	function generateTime() {
		const now = new Date();
		const year = now.getFullYear().toString().padStart(4, '0'); // 获取年份并转换为四位数
		const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 获取月份并转换为两位数
		const day = now.getDate().toString().padStart(2, '0'); // 获取日期并转换为两位数
		const hours = now.getHours().toString().padStart(2, '0'); // 获取小时并转换为两位数
		const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟并转换为两位数
		const seconds = now.getSeconds().toString().padStart(2, '0'); // 获取秒并转换为两位数
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
	async function submit() {
		try {
			applicationContent.value.applicationId = generateApplicationId(false);
			applicationContent.value.applicationTime = generateTime();
			console.log("applicationContent", applicationContent.value);

			// 上传身份证图片
			const idCardPromises = image.value.idCard.map(idCardFile => uploadFile(idCardFile, 'idCard'));

			// 上传营业执照图片
			let licensePromise = Promise.resolve();
			if (image.value.license) {
				console.log("上传营业执照");
				licensePromise = uploadFile(image.value.license[0], 'license');
			}
			// 等待所有上传操作完成
			await Promise.all([...idCardPromises, licensePromise]);

			// 所有上传操作完成后，调用 http.request
			const responseData = await http.request({
				url: "/api/application/insert_application",
				method: "POST",
				data: {
					application: applicationContent.value
				}
			});
			console.log("提交成功", responseData.data);
		} catch (err) {
			// 在这里处理上传文件过程中的错误
			console.log("上传文件失败", err);
		}
	}

	function test() {
		console.log("test", applicationContent.value)
		console.log("golbal", getApp().globalData.openid)
	}
</script>

<style lang="scss" scoped>
	@import "./application.scss";
</style>